package io.renren.modules.project.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.*;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import freemarker.template.Configuration;
import freemarker.template.Template;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.*;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.dop.entity.DopBmapEntity;
import io.renren.modules.project.entity.ProjectAuthachEntity;
import io.renren.modules.project.entity.ProjectExpachEntity;
import io.renren.modules.project.entity.ProjectSituationEntity;
import io.renren.modules.project.service.ProjectAuthachService;
import io.renren.modules.project.service.ProjectExpachService;
import io.renren.modules.project.service.ProjectSituationService;
import io.renren.modules.project.vo.AuthachVoEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 成果确认表
 *
 * @author ygg
 * @date 2021-06-15 11:52:17
 */
@RestController
@RequestMapping("project/authach")
public class ProjectAuthachController {
    @Autowired
    private ProjectAuthachService projectAuthachService;

    @Autowired
    private ProjectExpachService projectExpachService;

    @Autowired
    private ProjectSituationService projectSituationService;

    @Autowired
    public RedisUtils redisUtils;

    @Value("${wx.accountId}")
    private String accountId;

    @Value("${wx.accountSecret}")
    private String accountSecret;

    @Value("${spring.file.upResFolder}")
    private String upResFolder;

    /**
     * 分页查询
     */
    @RequestMapping("/page")
    @RequiresPermissions("project:authach:page")
    public R page(@RequestParam Map<String, Object> params){
        PageUtils page = projectAuthachService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        List<ProjectAuthachEntity> list = projectAuthachService.queryList(params);

        return R.ok().put("list", list);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{projectNo}")
    public R info(@PathVariable("projectNo") String projectNo){
		ProjectAuthachEntity projectAuthach = projectAuthachService.queryByPro(projectNo);
        ProjectSituationEntity sitEntity = projectSituationService.queryByProjectNo(projectNo);

        return R.ok().put("projectAuthach", projectAuthach).put("sitEntity",sitEntity);
    }

    /**
     * 保存(确认成果)
     */
    @SysLog("保存确认成果")
    @RequestMapping("/save")
//    @RequiresPermissions("project:authach:save")
    public R save(@RequestBody AuthachVoEntity authachVo){
        ProjectAuthachEntity entity = authachVo.getAuthachEntity();
        ProjectAuthachEntity projectAuthach = projectAuthachService.queryByPro(entity.getProjectNo());
        SysUserEntity userEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (projectAuthach == null) {
            projectAuthach = new ProjectAuthachEntity();
        }
        projectAuthach.setClientName(entity.getClientName());
        projectAuthach.setProjectNickname(entity.getProjectNickname());
        projectAuthach.setProjectNo(entity.getProjectNo());
        projectAuthach.setConfirmName(userEntity.getUsername());
        projectAuthach.setConfirmTime(new Date());
        projectAuthachService.insertOrUpdate(projectAuthach);

        ProjectSituationEntity situationEntity = projectSituationService.queryByProjectNo(entity.getProjectNo());
        situationEntity.setIsAach(1L);
        projectSituationService.updateById(situationEntity);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("project:authach:update")
    public R update(@RequestBody ProjectAuthachEntity projectAuthach){
		projectAuthachService.updateById(projectAuthach);

        return R.ok();
    }

    /**
     * 修改签名
     */
    @RequestMapping("/updateSign")
//    @RequiresPermissions("project:authach:update")
    public R updateSign(@RequestBody ProjectAuthachEntity projectAuthach){
        projectAuthachService.updateById(projectAuthach);
        ProjectSituationEntity situationEntity = projectSituationService.queryByProjectNo(projectAuthach.getProjectNo());
        situationEntity.setIsSign(1L);
        projectSituationService.updateById(situationEntity);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("project:authach:delete")
    public R delete(@RequestBody Long[] ids){
		projectAuthachService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @SysLog("上传客户附件")
    @RequestMapping("/upResFile")
    public R upResFile(@PathVariable MultipartFile file, @RequestParam("projectNo") String projectNo) {
        String fileName = "";
        try {
            String filePath = FileUtil.setFilePath(upResFolder, "(" + projectNo + ")" + file.getOriginalFilename(), true,false);
            File dest = new File(filePath);
            fileName = dest.getName();
            file.transferTo(dest);
        }catch (Exception ex){
            return R.error(ex.getMessage());
        }
        return R.ok().put("fileName", fileName);
    }

    /**
     * 导出调查表 Word文件
     * @param authachVo
     * @return
     */
    @SysLog("导出调查表Word")
    @RequestMapping("/exportWord")
    public void exportWord(HttpServletResponse response, HttpServletRequest request,@RequestBody AuthachVoEntity authachVo) {
        try {
            String projectNo = authachVo.getAuthachEntity().getProjectNo();
            projectAuthachService.save(authachVo.getAuthachEntity());
            projectExpachService.updateBatchById(authachVo.getAchList());
            // 缓存数据 查看是否有wxQrToken
            String wxQrToken = redisUtils.get("wxQrToken");
            List<ProjectExpachEntity> nList = new ArrayList<>();
            for(ProjectExpachEntity entity : authachVo.getAchList()) {
                if (entity.getChecked() != null && entity.getChecked() == true) {
                    nList.add(entity);
                }
            }
            authachVo.setAchList(nList);

            if (StringUtils.isNotBlank(wxQrToken) ) {
                ;
            } else {
                wxQrToken = WxQrCode.getAccessToken(accountId,accountSecret);
                // 将微信wxQrToken 放入缓存区
                redisUtils.set("wxQrToken", wxQrToken,1*60*60);
            }
            // 微信小程序跳转的页面
            String page = "pages/ach/ach";
            String imgData = WxQrCode.getminiqrQr(wxQrToken,projectNo,page,request);
            Map<String,Object> objectMap = MapEntityUtil.entityToMap(authachVo);

            objectMap.put("projectNickname",authachVo.getAuthachEntity().getProjectNickname());
            objectMap.put("clientName",authachVo.getAuthachEntity().getClientName());
            objectMap.put("achList",authachVo.getAchList());
            objectMap.put("codeImg", imgData.replaceAll("\n", ""));

            freemarker.template.Configuration cfg = new Configuration(Configuration.getVersion());
            cfg.setDefaultEncoding("UTF-8");
            cfg.setClassForTemplateLoading(FreeMarkerUtil.class, "/static/ftl");
            Template template = cfg.getTemplate("survey.ftl");

            response.reset();
            response.addHeader("Access-Control-Allow-Origin" , "*");
            response.setHeader("Access-Control-Allow-Credentials" ,"false");
            response.setHeader("Content-Disposition", "attachment; filename=\"map.doc\"");
            response.setContentType("application/msword; charset=UTF-8");

            template.process(objectMap, response.getWriter());

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 导出最终表 Word文件
     * @param params
     * @return
     */
    @SysLog("导出最终表Word")
    @RequestMapping("/exportResWord")
    public void exportResWord(HttpServletResponse response, HttpServletRequest request,@RequestParam Map<String, Object> params) {
        try {
            String projectNo = (String)params.get("projectNo");
            List<ProjectExpachEntity> list = projectExpachService.queryLastList(params);
            ProjectAuthachEntity authachEntity = projectAuthachService.queryByPro(projectNo);

            List<ProjectExpachEntity> nList = new ArrayList<>();
            for(ProjectExpachEntity entity : list) {
                if (entity.getChecked() != null && entity.getChecked() == true) {
                    nList.add(entity);
                }
            }

            // 缓存数据 查看是否有wxQrToken
            String wxQrToken = redisUtils.get("wxQrToken");
            if (StringUtils.isNotBlank(wxQrToken) ) {
                ;
            } else {
                wxQrToken = WxQrCode.getAccessToken(accountId,accountSecret);
                // 将微信wxQrToken 放入缓存区
                redisUtils.set("wxQrToken", wxQrToken,1*60*60);
            }
            // 微信小程序跳转的页面
            String page = "pages/ach/ach";
            String imgData = WxQrCode.getminiqrQr(wxQrToken,projectNo,page,request);
            Map<String,Object> objectMap = MapEntityUtil.entityToMap(authachEntity);
            objectMap.put("achList",nList);
            objectMap.put("codeImg", imgData.replaceAll("\n", "").replaceAll("\r\n",""));

            freemarker.template.Configuration cfg = new Configuration(Configuration.getVersion());
            cfg.setDefaultEncoding("UTF-8");
            cfg.setClassForTemplateLoading(FreeMarkerUtil.class, "/static/ftl");
            Template template = cfg.getTemplate("result.ftl");

            response.reset();
            response.addHeader("Access-Control-Allow-Origin" , "*");
            response.setHeader("Access-Control-Allow-Credentials" ,"false");
            response.setHeader("Content-Disposition", "attachment; filename=\"map.doc\"");
            response.setContentType("application/msword; charset=UTF-8");

            template.process(objectMap, response.getWriter());

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
